# -*- coding: utf-8 -*-

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import memcache
import models
import logging
import options
import datetime

# BLOG DEFAULTS

def init_blog():
    """Set the default content of the blog"""
    link = models.Link(name="Google App Engine",link="http://code.google.com/appengine/")
    link.put()
    link1 = models.Link(name="GAE group", link="http://groups.google.com/group/google-appengine")
    link1.put()
    category = models.Category(key_name="cat_a_category", 
                             category_name="A category", 
                             category_url="a_category")
    category.put()
    post = models.Post(key_name= 'post_hello_world',
                       title="Hello world!",
                       content="This is a sample post",
                       permalink="hello_world",
                       published=datetime.datetime.now(),
                       categories_keys = [category.key()],
                       draft=False,
                       creator=users.User("smalog@smaider.com")
                       )
    post.put()
    increment_counter('global_post_counter')
    increment_counter('cat_a_category_counter')


# PAGINATION    
    
def navigation(offset, total_count, limit=10):
    if offset:
      try:
        offset = int(offset)
      except:
        offset = 1
      else:
        offset = max(1, offset)
    else:
      offset = 1
    if offset>1:
        previous_list = range(1,offset)
        previous = offset -1
    else:
        previous_list = None
        previous = None
    last=((total_count-1)/limit)+1
    if last>offset:
        next_list = range(offset+1,last+1)
        next = offset + 1
    else:
        next_list = None
        next = None
    response = {'previous_list' : previous_list,
                'previous':previous,
                'current': offset,
                'next': next,
                'next_list': next_list,
                'last': last }
    return response


# SIDEBAR
  
def do_sidebar():  
    sidebar = u''
    constructors = {}
    #Categories
    def do_categories():
        cats = models.Category.all().order('category_name')
        str = u''
        if cats.count():
            str = u"<div><h3>Categorías</h3>\n<ul>"
            for cat in cats:
                str += '<li><a href="/category/' + cat.category_url + '">' + cat.category_name + '</a></li>\n'
            str += "</ul></div>\n"
        return str
    constructors['categories'] = do_categories
    #Pages
    def do_pages():
        pages = models.Post.all().filter('post_type', 'page').order('title')
        str = u''
        if pages.count():
            str += "<div><h3>Pages</h3>\n<ul>"
            for page in pages:
                str += '<li><a href="/page/' + page.permalink + '">' + page.title + '</a></li>\n'
            str += "</ul></div>\n"
        return str
    constructors['pages'] = do_pages
    #links
    def do_links():
        links = models.Link.all()
        str = u''
        if links.count():
            str += "<div><h3>Links</h3>\n<ul>"
            for link in links:
                str += '<li><a href="' + link.link + '">' + link.name + '</a></li>\n'
            str += "</ul></div>\n"
        return str
    constructors['links'] = do_links   
    #feed
    def do_feed():
        return '<div><a href="/feed"><img src="/static/images/feed.png"></a></div>'
    constructors['feed'] = do_feed
    #widgets
    def do_widget(key):
        str = u''
        try:
            widget = models.SidebarWidget.get(db.Key(key))
        except db.Error:
            return str
        if widget is not None:
            str += '<div>'
            if widget.title:
                str += '<h3>' + widget.title + '</h3>'
            return str + widget.text + '</div>'
    options = get_options()
    opt = options.sidebar_widgets
    for item in opt:
        if item in ("categories" , "pages", "links", "feed"):
            sidebar += constructors[item]()
        else:
            sidebar += do_widget(item)
    return sidebar


def get_sidebar():
    """get_sidebar()

    Checks the cache to see if there are cached sidebar.
    If not, call render_greetings and set the cache

    Returns:
    A string of HTML containing sidebar.
    """
    try:
        sidebar = memcache.get("sidebar")
    except:
        memcache.delete("sidebar")
        sidebar = None
    if sidebar is not None:
        logging.info('Memcache get succefull, sidebar retrived')
        return sidebar
    else:
        #memcache.flush_all()
        sidebar = do_sidebar()
        if not memcache.add("sidebar", sidebar):
            logging.info('Memcache set failed. Trying to cache sidebar:%s' % sidebar)
        else:
            logging.info('Memcache set succefull. Trying to cache sidebar:%s' % sidebar)
        return sidebar

# OPTIONS      

def get_options():
    """get_options()

    Checks the cache to see if there are cached sidebar.
    If not, call render_greetings and set the cache

    Returns:
    A string of HTML containing sidebar.
    """
    #memcache.delete("options")
    #print 'getting'
    try:
        opts = memcache.get("options_cache")
    except:
        memcache.delete("options_cache")
        opts = None
    if opts is not None:
        logging.info('Memcache get succefull, options retrived')
        return opts
    else:
        opts = options.Options()
        if not memcache.add("options_cache", opts):
            logging.info('Memcache set failed. Trying to cache opts:%s' % opts)
            #logging.info('Memcache set failed. Memcache stats:%s' % memcache.get_stats() )
        else:
            logging.info('Memcache set succefull. Trying to cache opts:%s' % opts)
        return opts

# COUNTERS

def increment_counter(counter_name):
    def inc():
        counter = models.Counter.get_by_key_name(counter_name)
        if counter is None:
            counter = models.Counter(key_name=counter_name, name=counter_name)
        counter.count += 1
        counter.put()
        logging.info("INCR %s: %s" % (counter_name,counter.count))
    db.run_in_transaction(inc)
    
def decrement_counter(counter_name):
    def dec():
        counter = models.Counter.get_by_key_name(counter_name)
        if counter:
            counter.count -= 1
            counter.put()
            logging.info("DECR %s: %s" % (counter_name,counter.count))
    db.run_in_transaction(dec)
        
def get_counter(counter_name):
    counter = models.Counter.get_by_key_name(counter_name)
    if counter:
        return counter.count
    else:
        return 0
        
def del_counter(counter_name):
    counter = models.Counter.get_by_key_name(counter_name)
    if counter:
        counter.delete()
